package minderupt.selenate.context;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;

import java.io.File;
import java.io.FileReader;

/**
 *
 */
public class ScriptEnvironment {

    private static Log LOGGER = LogFactory.getLog(ScriptEnvironment.class);

    private Context context;
    private Scriptable scope;
    private File currentBaseDirectory;



    public ScriptEnvironment(Context context, Scriptable scope) {
        this.context = context;
        this.scope = scope;
    }

    public void setCurrentBaseDirectory(File file) {
        this.currentBaseDirectory = file;
    }

    public void load(String scriptFilename) {

        // find new file
        if(LOGGER.isDebugEnabled()) LOGGER.debug("Loading script:  " + scriptFilename);
        File loadedScript = new File(this.currentBaseDirectory, scriptFilename);
        if(!loadedScript.exists()) {
            LOGGER.error("Unable to find new script file at " + loadedScript.getAbsolutePath());
            LOGGER.error("Working directory: " + this.currentBaseDirectory.getAbsolutePath());
            System.exit(5);
        }

        // set current working directory before evaluating script
        this.currentBaseDirectory = loadedScript.getAbsoluteFile().getParentFile();

        // bring into the execution environment
        try {
            LOGGER.info("Compiling: " + loadedScript.getAbsolutePath());
            this.context.evaluateReader(this.scope, new FileReader(loadedScript), loadedScript.getAbsolutePath(), 0, null);
        } catch(Exception e) {
            LOGGER.error("Unable to evaluation script: " + loadedScript.getAbsolutePath(), e);
            System.exit(1);
        }



    }





}
